﻿using System;
using System.Activities.Persistence;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Reactor.ServiceGrid.Workflows.Persistence
{
    public class TransferServiceStatusExtension : PersistenceParticipant
    {
        private string _donorCoreName;
        private readonly object _sync = new object();
        public const string DonorCoreXName = "DonorCoreName";

        internal void RecordDonorCoreName(string donorCoreName)
        {
            if (string.IsNullOrEmpty(donorCoreName)) throw new ArgumentNullException("donorCoreName");

            lock (_sync)
            {
                _donorCoreName = donorCoreName;
            }
        }

        internal string GetRecordedDonorCoreName()
        {
            lock (_sync)
            {
                return _donorCoreName;
            }
        }

        protected override void CollectValues(out IDictionary<XName, object> readWriteValues, out IDictionary<XName, object> writeOnlyValues)
        {
            readWriteValues = new Dictionary<XName, object>(1);

            lock (_sync)
            {
                readWriteValues.Add(DonorCoreXName, _donorCoreName);
            }

            writeOnlyValues = null;
        }

        protected override void PublishValues(IDictionary<XName, object> readWriteValues)
        {
            object loadedData;
            if (!readWriteValues.TryGetValue(DonorCoreXName, out loadedData)) return;

            lock (_sync)
            {
                _donorCoreName = (string) loadedData;
            }
        } 
    }
}
